package com.a1573595.musicplayer.playSong

import android.graphics.Bitmap
import com.a1573595.musicplayer.BasePresenter
import com.a1573595.musicplayer.player.PlayerService

class PlaySongPresenter(view: PlaySongView) : BasePresenter<PlaySongView>(view) {
    private lateinit var player: PlayerService

    fun setPlayerManager(player: PlayerService) {
        this.player = player

        fetchSongState()
    }

    fun fetchSongState() {
        player.getSong()?.let {
            view.updateSongState(it, player.isPlaying(), player.getProgress())

            view.showRepeat(player.isRepeat)
            view.showRandom(player.isRandom)
        }
    }

    fun updateRepeat(): Boolean {
        player.isRepeat = !player.isRepeat
        return player.isRepeat
    }
    fun getPlayerProgress(): Int {
        return player.getProgress()
    }
    fun getCurrentLyrics(currentTime: Int): String {//获取当前歌词（那一句）
        val currentTimeMillis = currentTime * 1000
        val lyrics = player.binder?.parsedLyrics ?: return ""
        return lyrics.findLast { it.first <= currentTimeMillis }?.second ?: ""

    }
    fun getCurrentLyricsPosition(currentTime: Int): Int {//获取当前歌词位置（那个位置position）
        val currentTimeMillis = currentTime * 1000
        val lyrics = player.binder?.parsedLyrics ?: return 0
        return lyrics.indexOfFirst { it.first > currentTimeMillis }.let {
            if (it == -1) lyrics.size - 1
            else it - 1
        }
    }
    fun getCurrentPicture(): Bitmap? {//获取当前图片
        val picture=player.binder?.dic_picture?:return null
        return picture
    }

    fun updateRandom(): Boolean {
        player.isRandom = !player.isRandom
        return player.isRandom
    }

    fun onSongPlay() {//播放或暂停
        if (!player.isPlaying()) {//如果没有播放
            player.play()
        } else {
            player.pause()//暂停
        }
    }

    fun skipToNext() = player.skipToNext()

    fun skipToPrevious() = player.skipToPrevious()

    fun seekTo(duration: Int) = player.seekTo(duration)
}